package io.github.talelin.latticy.service.impl;

import cn.hutool.core.util.StrUtil;
import io.github.talelin.latticy.service.AccuracyService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @authoer:wulongbo
 * @createDate:2022/8/23
 * @description:
 */
@Service
public class AccuracyServiceImpl implements AccuracyService {

    @Override
    public BigDecimal thresholdLimit(Integer amount, String price, String min, String max, Integer accuracy) {
        BigDecimal bgAmount = new BigDecimal(amount);
        BigDecimal bgPrice = new BigDecimal(price);
        BigDecimal result = bgAmount.multiply(bgPrice).setScale(2, rounding(accuracy));
        if (StrUtil.isEmpty(min) && StrUtil.isEmpty(max)) {
            return result;
        }
        if (StrUtil.isNotEmpty(min)) {
            if (result.compareTo(new BigDecimal(min)) < 0) {
                return new BigDecimal(min);
            }
        }
        if (StrUtil.isNotEmpty(max)) {
            if (result.compareTo(new BigDecimal(max)) > 0) {
                return new BigDecimal(max);
            }
        }
        return result;
    }


    /**
     * 取整方式
     *
     * @param accuracy
     * @return
     */
    private Integer rounding(Integer accuracy) {
        switch (accuracy) {
            case BigDecimal.ROUND_UP:
                return BigDecimal.ROUND_UP;
            case BigDecimal.ROUND_DOWN:
                return BigDecimal.ROUND_DOWN;
            case BigDecimal.ROUND_CEILING:
                return BigDecimal.ROUND_CEILING;
            case BigDecimal.ROUND_FLOOR:
                return BigDecimal.ROUND_FLOOR;
            case BigDecimal.ROUND_HALF_UP:
                return BigDecimal.ROUND_HALF_UP;
            case BigDecimal.ROUND_HALF_DOWN:
                return BigDecimal.ROUND_HALF_DOWN;
            case BigDecimal.ROUND_HALF_EVEN:
                return BigDecimal.ROUND_HALF_EVEN;
            case BigDecimal.ROUND_UNNECESSARY:
                return BigDecimal.ROUND_UNNECESSARY;
            default:
                return BigDecimal.ROUND_UP;
        }
    }

}
